<template>
  <div>
    <el-card>
      <template #header>
        <div class="card-header">
          <span>网球教学管理</span>
        </div>
      </template>
      
      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="queryForm.title"
          placeholder="请输入标题"
          style="width: 200px; margin-right: 10px"
        />
        <el-select
          v-model="queryForm.category"
          placeholder="请选择类别"
          style="width: 150px; margin-right: 10px"
          clearable
        >
          <el-option label="基础教学" value="基础教学" />
          <el-option label="进阶技巧" value="进阶技巧" />
          <el-option label="战术指导" value="战术指导" />
          <el-option label="体能训练" value="体能训练" />
        </el-select>
        <el-button type="primary" @click="getList">搜索</el-button>
        <el-button @click="handleReset">重置</el-button>
        <el-button type="primary" @click="handleAdd">新增教学</el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="tableData" style="width: 100%" stripe>
        <el-table-column prop="id" label="ID" width="60" />
        <el-table-column prop="title" label="标题" />
        <el-table-column prop="category" label="类别" width="100" />
        <el-table-column prop="level" label="等级" width="80" />
        <el-table-column prop="introduction" label="简介" show-overflow-tooltip />
        <el-table-column label="视频" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.videoUrl" 
              type="text" 
              @click="previewVideo(scope.row)"
            >
              预览
            </el-button>
            <span v-else>无视频</span>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button type="text" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button type="text" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="queryForm.pageNum"
          v-model:page-size="queryForm.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新增教学' : '编辑教学'"
      width="700px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="标题" prop="title" required>
          <el-input v-model="form.title" placeholder="请输入标题" />
        </el-form-item>
        <el-form-item label="类别" prop="category" required>
          <el-select v-model="form.category" placeholder="请选择类别">
            <el-option label="基础教学" value="基础教学" />
            <el-option label="进阶技巧" value="进阶技巧" />
            <el-option label="战术指导" value="战术指导" />
            <el-option label="体能训练" value="体能训练" />
          </el-select>
        </el-form-item>
        <el-form-item label="等级" prop="level" required>
          <el-select v-model="form.level" placeholder="请选择等级">
            <el-option label="初级" value="初级" />
            <el-option label="中级" value="中级" />
            <el-option label="高级" value="高级" />
            <el-option label="专业" value="专业" />
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="introduction" required>
          <el-input
            v-model="form.introduction"
            type="textarea"
            :rows="3"
            placeholder="请输入简介"
          />
        </el-form-item>
        <el-form-item label="内容" prop="content" required>
          <el-input
            v-model="form.content"
            type="textarea"
            :rows="6"
            placeholder="请输入详细内容"
          />
        </el-form-item>
        <el-form-item label="视频上传" required>
          <el-upload
            class="video-upload"
            drag
            :action="uploadUrl"
            :headers="uploadHeaders"
            :on-success="handleUploadSuccess"
            :on-error="handleUploadError"
            :before-upload="beforeUpload"
            :show-file-list="false"
            accept="video/*"
          >
            <div v-if="!form.videoUrl">
              <el-icon class="el-icon--upload"><upload-filled /></el-icon>
              <div class="el-upload__text">
                拖拽视频到此处或 <em>点击上传</em>
              </div>
            </div>
            <div v-else class="video-preview">
              <video :src="form.videoUrl" controls class="uploaded-video" />
              <el-button 
                type="danger" 
                size="small" 
                @click.stop="removeVideo"
              >
                删除视频
              </el-button>
            </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 视频预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="视频预览"
      width="600px"
    >
      <video
        v-if="currentVideoUrl"
        :src="currentVideoUrl"
        controls
        style="width: 100%; height: 400px"
      />
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { UploadFilled } from '@element-plus/icons-vue'
import { teachingList,teachingAdd,teachingUpdate,teachingDelete } from '@/request/teaching'
// 表格数据
const tableData = ref([])
const total = ref(0)

// 搜索表单
const queryForm = reactive({
  title: '',
  category: '',
  level: '',
  pageNum: 1,
  pageSize: 10
})

const getList = () => {
  teachingList(queryForm).then(res => {
    tableData.value = res.records
    total.value = res.total
  })
}

// 对话框
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref()

// 表单数据
const form = reactive({
  id: null,
  title: '',
  category: '',
  level: '',
  introduction: '',
  content: '',
  videoUrl: ''
})

// 视频预览
const previewDialogVisible = ref(false)
const currentVideoUrl = ref('')

// 表单验证规则
const rules = {
  title: [
    { required: true, message: '请输入标题', trigger: 'blur' }
  ],
  category: [
    { required: true, message: '请选择类别', trigger: 'change' }
  ],
  level: [
    { required: true, message: '请选择等级', trigger: 'change' }
  ],
  introduction: [
    { required: true, message: '请输入简介', trigger: 'blur' }
  ],
  content: [
    { required: true, message: '请输入内容', trigger: 'blur' }
  ]
}

// 上传配置
const uploadUrl = '/api/system/file/uploadFile'
const uploadHeaders = {
  Authorization: localStorage.getItem('token') || ''
}

// 重置
const handleReset = () => {
  searchForm.title = ''
  searchForm.category = ''
  getList()
}

// 新增
const handleAdd = () => {
  dialogType.value = 'add'
  resetForm()
  dialogVisible.value = true
}

// 编辑
const handleEdit = (row) => {
  dialogType.value = 'edit'
  row.videoUrl = '/api'+row.videoUrl
  Object.assign(form, row)
  dialogVisible.value = true
}

// 删除
const handleDelete = (row) => {
  ElMessageBox.confirm(
    '确认删除这条教学内容吗？',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    teachingDelete(row.id).then(res => {
      ElMessage.success('删除成功')
      getList()
    })
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      // 提交时检查
      if (!form.videoUrl) {
        ElMessage.error('请上传教学视频！')
        return  // 阻止提交
      }
      if(form.videoUrl.startsWith('/api')){
        form.videoUrl = form.videoUrl.substring(4)
      }
      if (dialogType.value === 'add') {
        teachingAdd(form).then(res => {
          ElMessage.success('新增成功')
          getList()
        })
      } else {
        teachingUpdate(form).then(res => {
          ElMessage.success('编辑成功')
          getList()
        })
      }
      dialogVisible.value = false
      getList()
    }
  })
}

// 重置表单
const resetForm = () => {
  Object.assign(form, {
    id: null,
    title: '',
    category: '',
    level: '',
    introduction: '',
    content: '',
    videoUrl: ''
  })
}

// 关闭对话框
const handleDialogClose = () => {
  formRef.value.resetFields()
  resetForm()
}

// 视频上传成功
const handleUploadSuccess = (response, file) => {
  form.videoUrl = ('/api'+(response.data || URL.createObjectURL(file.raw)))
  ElMessage.success('视频上传成功')
}

// 视频上传失败
const handleUploadError = (error) => {
  ElMessage.error('视频上传失败')
}

// 上传前检查
const beforeUpload = (file) => {
  const isVideo = file.type.startsWith('video/')
  const isLt50M = file.size / 1024 / 1024 < 100

  if (!isVideo) {
    ElMessage.error('只能上传视频文件！')
    return false
  }
  if (!isLt50M) {
    ElMessage.error('视频大小不能超过 100MB！')
    return false
  }
  return true
}

// 删除视频
const removeVideo = () => {
  form.videoUrl = ''
}

// 预览视频
const previewVideo = (row) => {
  console.log(row.videoUrl)
  currentVideoUrl.value = '/api'+row.videoUrl
  previewDialogVisible.value = true
}

// 分页处理
const handleSizeChange = (val) => {
  pageSize.value = val
  getList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  getList()
}

// 初始化
onMounted(() => {
  getList()
})
</script>

<style scoped>
.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}

.video-upload {
  width: 100%;
}

.video-preview {
  text-align: center;
}

.uploaded-video {
  width: 100%;
  max-height: 300px;
  margin-bottom: 10px;
}

:deep(.el-upload-dragger) {
  width: 100%;
}
</style>